<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Configuration
 *
 * @author MinhNguyen
 */
// Include twitteroauth
include 'Libs/twitter/twitteroauth.php';

class Twitter{
    //put your code here
    public $tweet;
    public static $instance;
    public $config = array(
        'consume_key' => 'WFVVsVc2HAzFmsQ38S5NMg',
        'consume_secret' => 'uJZQsCkzrBzNDCm7TNmtC3R2geEGPSlFi8UXGUrZulE',
    );
    
    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function __get($name) {
        return $this->$name;
    }
    
    public function __set($name, $value) {
        $this->$name = $value;
    } 
    
    public function __construct() {
        //allocate your stuff
    }
    
    public static function withData($token = NULL, $tokensecret = NULL){
        $instance = self::getInstance();
        $instance->tweet = new TwitterOAuth($instance->config['consume_key'], $instance->config['consume_secret'], $token, $tokensecret);
        return $instance;
    }
    
    public static function getAuthorization($oauth_callback) {
        $instance = self::withData();
        $token = $instance->tweet->getRequestToken($oauth_callback);
        $newURL = $instance->tweet->getAuthorizeURL($token, TRUE);
        header("Location: $newURL");
        $_SESSION["token"] = $token["oauth_token"];
        $_SESSION["secret"] = $token["oauth_token_secret"];
    }
    
    public static function getCredentials() {
        $oauth_verifier = $_GET['oauth_verifier'];
        $instance = self::withData($_SESSION["token"], $_SESSION["secret"]);
        $credentials = $instance->tweet->getAccessToken($oauth_verifier);
        $db = Database::getInstance();
        $id = $db->getID("twitters", "id");
        $userId = $_SESSION['userid'];
        $oauthtoken = $credentials["oauth_token"];
        $oauthtokensecret = $credentials["oauth_token_secret"];
        $twitterid = $credentials["user_id"];
        $screenname = $credentials["screen_name"];
        $query = "INSERT INTO twitters (id, userid, oauthtoken, oauthtokensecret,
            twitterid, screenname) VALUES ('$id', '$userId', 
            '$oauthtoken', '$oauthtokensecret', '$twitterid', '$screenname')";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            return "true";
        }
        else {
            return "false";
        }
    }
    
    public static function postTweet($message){
        if (isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $userId = $_SESSION['userid'];
            $query = "SELECT * FROM twitters WHERE userid = '$userId'";
            $result = $db->query($query);
             if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow == 1) {
                    $rows = $result->dataTable->rows[0];
                    if(strlen($message) < 140){
                        $instance = self::withData($rows['oauthtoken'], $rows['oauthtokensecret']);
                        $response = $instance->tweet->post('statuses/update', array('status' => $message));                        
                        if ($response != 200) {
                            if($response == 403)
                                return "Cannot send a message twice.";
                            else
                                //Do something if the request was unsuccessful
                                return "There was an error posting the message.";
                        }
                        return "Posted";
                    }else{
                        return "The message is too long";
                    }
                }else {
                    return "Not found data";
                }
            }else {
                return "Cannot connect database";
            }
        }else {
            return "No user log in";
        }
    }
    
    public static function getTwitters() {
        if (isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $userId = $_SESSION['userid'];
            $query = "SELECT * FROM twitters WHERE userid = '$userId'";
            $result = $db->query($query);
             if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $name = $row['screenname'];
                        $id = $row['twitterid'];
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                    }
                    return array(
                        "screenname" => $username,
                        "id" => $userid
                    );
                }else {
                    return array(
                        "screenname" => 'undefined',
                        "id" => 'undefined'
                    );
                }
            }else {
                return array(
                    "screenname" => 'undefined',
                    "id" => 'undefined'
                );
            }
        }else {
            return array(
                "screenname" => 'undefined',
                "id" => 'undefined'
            );
        }
    }
    
    public static function deleteTwitter($twitterid) {
        if(isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $query = "DELETE FROM twitters WHERE twitterid = '$twitterid'"; 
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            }
            else {
                return "false";
            }
        }
        else {
            return "false";
        }
    }
}
?>
